<?php

/**
 * StoreItem form.
 *
 * @package    ProdAssistant
 * @subpackage form
 * @author     Paweł Świtalla
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class StoreItemForm extends BaseStoreItemForm
{
  protected $fields;
  public $itemCategory;
  
  public function __construct($category, $fields = array(), $object = null)
  {
    $this->itemCategory = $category;
    $this->fields = array('name', 'quantity');
    if(count($fields))
    {
      $this->fields = array_merge($this->fields, $fields);
    }
    parent::__construct($object);
  }
  
  public function configure()
  {
    $category = Doctrine_Core::getTable('Category')->findBy('name', $this->itemCategory)->getFirst();
    $parameters = array();
    if($category instanceof Category)
    {
      $parameters = $category->getParametersHierarchy()->toArray();
      $this->getWidget("quantity")->setLabel("Ilość [".$category->getQuantityUnit()."]");
    }
    
    foreach($parameters as $parameter => $settings)
    {
      $form = $this->setWidget($settings['name'], new sfWidgetFormInput());
      $name = explode("_", ucfirst($settings['name']));
      $form->getWidget($settings['name'])->setLabel($name[0]." [".$settings['unit']."]");
      $this->setValidator($settings['name'], new sfValidatorString());
      $this->fields[] = $settings['name'];
    }
    
    if($this->getObject()->exists())
    {
      foreach($parameters as $parameter => $settings)
      {
        $value = Doctrine_Query::create()
                ->select("s.{$settings['name']}")
                ->from('StoreItem s')
                ->where('s.id = ?', $this->getObject()->getId())
                ->fetchOne()
                ->toArray();
        $this->setDefault($settings['name'], $value[$settings['name']]);
      }
    }
    
    $this->getValidatorSchema()->setOption('allow_extra_fields', true);
    $this->getValidatorSchema()->setOption('filter_extra_fields', false);
    $this->useFields($this->fields);
    $this->getWidget('name')->setLabel('Nazwa');
  }
}
